package com.android.lovely.framework

import android.content.Context
import android.os.Bundle
import android.os.LocaleList
import android.view.LayoutInflater
import android.view.View
import android.widget.Toast
import androidx.annotation.UiThread
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import androidx.viewbinding.ViewBinding
import com.android.lovely.LifecycleApplication
import com.android.lovely.R
import com.android.lovely.aav.PreferentialManager
import com.android.lovely.api.manager.contactUrl
import com.android.lovely.api.manager.netWorkChangeState
import com.android.lovely.dialog.CenterLoadingDialog
import com.android.lovely.ext.fullScreen
import com.android.lovely.ext.saveAs
import com.android.lovely.ext.saveAsUnChecked
import com.android.lovely.ext.startWebView
import com.android.lovely.framework.UIController.showLoadingUiState
import com.android.lovely.framework.UIController.showToastUiState
import com.android.lovely.manager.KVStore
import com.android.lovely.ui.activity.LoginActivity
import com.android.lovely.ui.activity.PayActivity
import com.android.lovely.ui.activity.SetLovelyActivity
import com.android.lovely.ui.activity.SplashActivity
import com.android.lovely.ui.dialog.PayDialog
import com.android.lovely.ui.dialog.showLovelyDialog
import com.kotlin.extensions.context.ActivityExt.navBarLightMode
import com.kotlin.extensions.context.ActivityExt.statusBarLightMode
import com.kotlin.extensions.context.ContextExt.startPage
import com.kotlin.extensions.context.ContextExt.startPageClearTask
import com.kotlin.extensions.coroutine.CoroutineExt.launchSafety
import kotlinx.coroutines.flow.collectLatest
import java.lang.reflect.ParameterizedType
import java.util.Locale
import java.util.concurrent.atomic.AtomicBoolean

/**
 *
 * @author why
 * @date 2025/3/6 19:17
 */
abstract class BaseActivity<DB : ViewBinding> : AppCompatActivity() {
    protected lateinit var mBinding: DB

    fun setContentLayout() {
        val type = javaClass.genericSuperclass
        val vbClass: Class<DB> =
            type?.saveAs<ParameterizedType>()?.actualTypeArguments?.get(0)?.saveAs()
                ?: throw IllegalArgumentException("unknown generic type")
        val method = vbClass.getDeclaredMethod("inflate", LayoutInflater::class.java)
        mBinding = method.invoke(this, layoutInflater)?.saveAsUnChecked()
            ?: throw IllegalArgumentException("unknown generic type")
        setContentView(mBinding.root)
    }

    private var centerLoadingDialog: CenterLoadingDialog? = null

    private var isLoginException: AtomicBoolean = AtomicBoolean(false)

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentLayout()
        if (transparentSystemBar) fullScreen()
        if (this@BaseActivity !is SplashActivity && this@BaseActivity !is LoginActivity) {
            PreferentialManager.isSecondLevelPageShown = true
        }
        statusBarLightMode = false
        navBarLightMode = false
        initView(savedInstanceState)
        lifecycleScope.launchSafety {
            repeatOnLifecycle(Lifecycle.State.STARTED) {
                netWorkChangeState.collectLatest {
                    when (it) {
                        -1 -> onRecharge()
                        -2 -> {
                            onLoginExpire()
                        }

                        -3 -> {
                            onAccountBand()
                        }
                    }
                }
            }
        }
        lifecycleScope.launchSafety {
            repeatOnLifecycle(Lifecycle.State.RESUMED) {
                showToastUiState.collectLatest {
                    if (it.isResumed) return@collectLatest
                    it.isResumed = true
                    showToast(it.msg)
                }
            }
        }
        lifecycleScope.launchSafety() {
            repeatOnLifecycle(Lifecycle.State.RESUMED) {
                showLoadingUiState.collectLatest { it ->
                    if (it.isResumed) return@collectLatest
                    it.isResumed = true
                    if (it.show) {
                        showLoading(it.canCancel)
                    } else {
                        dismissLoading()
                    }
                }
            }
        }
        lifecycleScope.launchSafety {
            initData()
        }
    }

    /**
     * 初始化布局
     * @param savedInstanceState Bundle?
     */
    abstract fun initView(savedInstanceState: Bundle?)

    /**
     * 初始化数据
     */
    open suspend fun initData() {

    }

    open var transparentSystemBar: Boolean = true

    private fun onAccountBand() {
        if (isLoginException.get().not()) {
            isLoginException.set(true)
            showLovelyDialog {
                setDialogTitle(getString(R.string.account_error_title))
                setDialogMessage(getString(R.string.account_error))
                setNegativeButton(getString(R.string.ok)) {
                    isLoginException.set(false)
                    if (this@BaseActivity !is SetLovelyActivity && this@BaseActivity !is SplashActivity) {
                        startPageClearTask<SplashActivity>("logout" to true)
                    }
                }

                setPositiveButton(getString(R.string.contact_us)) {
                    if (this@BaseActivity !is SetLovelyActivity && this@BaseActivity !is SplashActivity) {
                        LifecycleApplication.finishAll()
                        startPage<SplashActivity>("logout" to true)
                        contactUrl.ifEmpty { KVStore.system?.contactUsUrl }
                            ?.let {
                                startWebView(getString(R.string.contact_us), it)
                            }
                    } else {
                        contactUrl.ifEmpty { KVStore.system?.contactUsUrl }
                            ?.let {
                                startWebView(getString(R.string.contact_us), it)
                            }
                    }

                }
            }
        }
    }

    private fun onLoginExpire() {
        if (isLoginException.get().not()) {
            isLoginException.set(true)
            showLovelyDialog {
                setDialogTitle(getString(R.string.login_expire))
                setDialogMessage(getString(R.string.login_expire_message))
                showOnlyPositiveButton()
                setPositiveButton {
                    isLoginException.set(false)
                    if (this@BaseActivity !is SetLovelyActivity && this@BaseActivity !is SplashActivity) {
                        startPageClearTask<SplashActivity>("logout" to true)
                    }
                }
            }
        }
    }


    fun onBack() {
        onBackPressedDispatcher.onBackPressed()
    }

    fun onBack(v: View) {
        onBackPressedDispatcher.onBackPressed()
    }

    override fun attachBaseContext(newBase: Context) {
        super.attachBaseContext(attachContext(newBase))
    }

    private fun attachContext(context: Context): Context {
        return updateResources(context)
    }

    private fun updateResources(context: Context): Context {
        val locale = KVStore.appLanguage.code
        val configuration = context.resources.configuration
        configuration.setLocale(Locale(locale))
        configuration.setLocales(LocaleList(Locale(locale)))
        return context.createConfigurationContext(configuration)
    }

    open fun onRecharge() {
        PayDialog().show(supportFragmentManager)
    }

    @UiThread
    private fun showToast(message: String?) {
        if (message.isNullOrEmpty()) return
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show()
    }

    @UiThread
    open fun showLoading(cancelable: Boolean = true) {
        runCatching {
            if (centerLoadingDialog == null) {
                centerLoadingDialog = CenterLoadingDialog(this)
            }
            if (centerLoadingDialog?.isShowing == true) {
                return
            }
            if (isFinishing) {
                return
            }
            centerLoadingDialog?.apply {
                canCancel(cancelable)
            }?.show()
        }
    }

    @UiThread
    open fun dismissLoading() {
        runCatching {
            if (isFinishing) {
                return
            }

            centerLoadingDialog?.let {
                if (it.isShowing) {
                    it.dismiss()
                }
            }
            centerLoadingDialog = null
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        dismissLoading()
        centerLoadingDialog = null
    }
}